package LeetCode;

import java.util.HashMap;

/**
 * @Author: Dijah
 * @Date: 2023/3/28 11:13
 * @Desc: 字符串的排列
 */
public class code567_checkInclusion {

    public static boolean checkInclusion(String s1, String s2) {
        //need是需要s1中的
        HashMap<Character,Integer> need = new HashMap<>();
        //window是窗体中的
        HashMap<Character,Integer> window = new HashMap<>();
        for(int i = 0; i < s1.length(); i++){
            char c = s1.charAt(i);
            need.put(c, need.getOrDefault(c, 0) + 1);
        }

        int left = 0;
        int right = 0;
        //
        int valid = 0;
        while(right < s2.length()){
            char c = s2.charAt(right);
            //右扩窗口
            right++;
            if(need.containsKey(c)){
                window.put(c,window.getOrDefault(c,0) + 1);
                if(window.get(c).equals(need.get(c))){
                    valid++;
                }
            }
            //判断左侧窗口是否需要收缩
            while(right - left >= s1.length()){
                //判断是否找到了合法的字符串
                if(valid == need.size()){
                    //如果找到了
                    return true;
                }
                //窗口收缩
                char d = s2.charAt(left);
                left++;
                if (need.containsKey(d)) {
                    if (window.get(d).equals(need.get(d))){
                        valid--;
                    }
                    window.put(d, window.getOrDefault(d, 0) - 1);
                }
            }
        }
        return false;
    }


    public static void main(String[] args) {
        String s1 = "ab";
        String s2 = "adbaooo";
        boolean b = checkInclusion(s1,s2);
        System.out.println(b);
    }
}
